/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gruposp2p.aularest.model.controller;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.gruposp2p.aularest.model.Course;
import org.gruposp2p.aularest.model.Subject;
import java.util.ArrayList;
import java.util.Collection;
import org.gruposp2p.aularest.model.Coursegroup;
import org.gruposp2p.aularest.model.controller.exceptions.IllegalOrphanException;
import org.gruposp2p.aularest.model.controller.exceptions.NonexistentEntityException;
import org.gruposp2p.aularest.model.controller.exceptions.PreexistingEntityException;

/**
 *
 * @author jj
 */
public class CourseJpaController {

    public CourseJpaController() {
        emf = Persistence.createEntityManagerFactory("AulaRest_PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Course course) throws PreexistingEntityException, Exception {
        if (course.getSubjectCollection() == null) {
            course.setSubjectCollection(new ArrayList<Subject>());
        }
        if (course.getCoursegroupCollection() == null) {
            course.setCoursegroupCollection(new ArrayList<Coursegroup>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Subject> attachedSubjectCollection = new ArrayList<Subject>();
            for (Subject subjectCollectionSubjectToAttach : course.getSubjectCollection()) {
                subjectCollectionSubjectToAttach = em.getReference(subjectCollectionSubjectToAttach.getClass(), subjectCollectionSubjectToAttach.getId());
                attachedSubjectCollection.add(subjectCollectionSubjectToAttach);
            }
            course.setSubjectCollection(attachedSubjectCollection);
            Collection<Coursegroup> attachedCoursegroupCollection = new ArrayList<Coursegroup>();
            for (Coursegroup coursegroupCollectionCoursegroupToAttach : course.getCoursegroupCollection()) {
                coursegroupCollectionCoursegroupToAttach = em.getReference(coursegroupCollectionCoursegroupToAttach.getClass(), coursegroupCollectionCoursegroupToAttach.getId());
                attachedCoursegroupCollection.add(coursegroupCollectionCoursegroupToAttach);
            }
            course.setCoursegroupCollection(attachedCoursegroupCollection);
            em.persist(course);
            for (Subject subjectCollectionSubject : course.getSubjectCollection()) {
                Course oldCourseIdOfSubjectCollectionSubject = subjectCollectionSubject.getCourseId();
                subjectCollectionSubject.setCourseId(course);
                subjectCollectionSubject = em.merge(subjectCollectionSubject);
                if (oldCourseIdOfSubjectCollectionSubject != null) {
                    oldCourseIdOfSubjectCollectionSubject.getSubjectCollection().remove(subjectCollectionSubject);
                    oldCourseIdOfSubjectCollectionSubject = em.merge(oldCourseIdOfSubjectCollectionSubject);
                }
            }
            for (Coursegroup coursegroupCollectionCoursegroup : course.getCoursegroupCollection()) {
                Course oldCourseIdOfCoursegroupCollectionCoursegroup = coursegroupCollectionCoursegroup.getCourseId();
                coursegroupCollectionCoursegroup.setCourseId(course);
                coursegroupCollectionCoursegroup = em.merge(coursegroupCollectionCoursegroup);
                if (oldCourseIdOfCoursegroupCollectionCoursegroup != null) {
                    oldCourseIdOfCoursegroupCollectionCoursegroup.getCoursegroupCollection().remove(coursegroupCollectionCoursegroup);
                    oldCourseIdOfCoursegroupCollectionCoursegroup = em.merge(oldCourseIdOfCoursegroupCollectionCoursegroup);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCourse(course.getId()) != null) {
                throw new PreexistingEntityException("Course " + course + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Course course) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Course persistentCourse = em.find(Course.class, course.getId());
            Collection<Subject> subjectCollectionOld = persistentCourse.getSubjectCollection();
            Collection<Subject> subjectCollectionNew = course.getSubjectCollection();
            Collection<Coursegroup> coursegroupCollectionOld = persistentCourse.getCoursegroupCollection();
            Collection<Coursegroup> coursegroupCollectionNew = course.getCoursegroupCollection();
            List<String> illegalOrphanMessages = null;
            for (Subject subjectCollectionOldSubject : subjectCollectionOld) {
                if (!subjectCollectionNew.contains(subjectCollectionOldSubject)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Subject " + subjectCollectionOldSubject + " since its courseId field is not nullable.");
                }
            }
            for (Coursegroup coursegroupCollectionOldCoursegroup : coursegroupCollectionOld) {
                if (!coursegroupCollectionNew.contains(coursegroupCollectionOldCoursegroup)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Coursegroup " + coursegroupCollectionOldCoursegroup + " since its courseId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Subject> attachedSubjectCollectionNew = new ArrayList<Subject>();
            for (Subject subjectCollectionNewSubjectToAttach : subjectCollectionNew) {
                subjectCollectionNewSubjectToAttach = em.getReference(subjectCollectionNewSubjectToAttach.getClass(), subjectCollectionNewSubjectToAttach.getId());
                attachedSubjectCollectionNew.add(subjectCollectionNewSubjectToAttach);
            }
            subjectCollectionNew = attachedSubjectCollectionNew;
            course.setSubjectCollection(subjectCollectionNew);
            Collection<Coursegroup> attachedCoursegroupCollectionNew = new ArrayList<Coursegroup>();
            for (Coursegroup coursegroupCollectionNewCoursegroupToAttach : coursegroupCollectionNew) {
                coursegroupCollectionNewCoursegroupToAttach = em.getReference(coursegroupCollectionNewCoursegroupToAttach.getClass(), coursegroupCollectionNewCoursegroupToAttach.getId());
                attachedCoursegroupCollectionNew.add(coursegroupCollectionNewCoursegroupToAttach);
            }
            coursegroupCollectionNew = attachedCoursegroupCollectionNew;
            course.setCoursegroupCollection(coursegroupCollectionNew);
            course = em.merge(course);
            for (Subject subjectCollectionNewSubject : subjectCollectionNew) {
                if (!subjectCollectionOld.contains(subjectCollectionNewSubject)) {
                    Course oldCourseIdOfSubjectCollectionNewSubject = subjectCollectionNewSubject.getCourseId();
                    subjectCollectionNewSubject.setCourseId(course);
                    subjectCollectionNewSubject = em.merge(subjectCollectionNewSubject);
                    if (oldCourseIdOfSubjectCollectionNewSubject != null && !oldCourseIdOfSubjectCollectionNewSubject.equals(course)) {
                        oldCourseIdOfSubjectCollectionNewSubject.getSubjectCollection().remove(subjectCollectionNewSubject);
                        oldCourseIdOfSubjectCollectionNewSubject = em.merge(oldCourseIdOfSubjectCollectionNewSubject);
                    }
                }
            }
            for (Coursegroup coursegroupCollectionNewCoursegroup : coursegroupCollectionNew) {
                if (!coursegroupCollectionOld.contains(coursegroupCollectionNewCoursegroup)) {
                    Course oldCourseIdOfCoursegroupCollectionNewCoursegroup = coursegroupCollectionNewCoursegroup.getCourseId();
                    coursegroupCollectionNewCoursegroup.setCourseId(course);
                    coursegroupCollectionNewCoursegroup = em.merge(coursegroupCollectionNewCoursegroup);
                    if (oldCourseIdOfCoursegroupCollectionNewCoursegroup != null && !oldCourseIdOfCoursegroupCollectionNewCoursegroup.equals(course)) {
                        oldCourseIdOfCoursegroupCollectionNewCoursegroup.getCoursegroupCollection().remove(coursegroupCollectionNewCoursegroup);
                        oldCourseIdOfCoursegroupCollectionNewCoursegroup = em.merge(oldCourseIdOfCoursegroupCollectionNewCoursegroup);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = course.getId();
                if (findCourse(id) == null) {
                    throw new NonexistentEntityException("The course with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Course course;
            try {
                course = em.getReference(Course.class, id);
                course.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The course with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Subject> subjectCollectionOrphanCheck = course.getSubjectCollection();
            for (Subject subjectCollectionOrphanCheckSubject : subjectCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Course (" + course + ") cannot be destroyed since the Subject " + subjectCollectionOrphanCheckSubject + " in its subjectCollection field has a non-nullable courseId field.");
            }
            Collection<Coursegroup> coursegroupCollectionOrphanCheck = course.getCoursegroupCollection();
            for (Coursegroup coursegroupCollectionOrphanCheckCoursegroup : coursegroupCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Course (" + course + ") cannot be destroyed since the Coursegroup " + coursegroupCollectionOrphanCheckCoursegroup + " in its coursegroupCollection field has a non-nullable courseId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(course);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Course> findCourseEntities() {
        return findCourseEntities(true, -1, -1);
    }

    public List<Course> findCourseEntities(int maxResults, int firstResult) {
        return findCourseEntities(false, maxResults, firstResult);
    }

    private List<Course> findCourseEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Course as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Course findCourse(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Course.class, id);
        } finally {
            em.close();
        }
    }

    public int getCourseCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Course as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
